package com.situ.vivamarket.controller.front;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.GifCaptcha;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.pagehelper.Page;
import com.situ.vivamarket.model.*;
import com.situ.vivamarket.model.front.MemberAddress;
import com.situ.vivamarket.model.search.GoodsSearchBean;
import com.situ.vivamarket.service.*;
import com.situ.vivamarket.service.front.MemberAddrService;
import com.situ.vivamarket.util.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/vm/front")
public class FrontIndexController {
    GoodsService goodsService;
    MemberService memberService;
    OrderService orderService;
    MemberAddrService memberAddrService;
    CategoryService categoryService;

    @Value("${alipay.alipay-public-key}")
    private String alipayPublicKey;

    //依赖注入
    @Autowired
    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }
    @Autowired
    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }
    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
    @Autowired
    public void setMemberAddrService(MemberAddrService memberAddrService) {
        this.memberAddrService = memberAddrService;
    }
    @Autowired
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    //      跳转到商城首页
    @GetMapping("/index")
    public String index(Map<String, Object> map) {
        GoodsSearchBean gsb = new GoodsSearchBean();
        /*todo:统计周销量最佳*/
        List<Goods> goods = this.goodsService.getAllGoods(gsb, new Page<>(1, 12));
        List<Category> cats= this.categoryService.findAll();
        map.put("goods", goods);
        map.put("cats", cats);
        return "front/common/index";
    }



    //      响应图片验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 创建 GIF 动态验证码
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(100, 45, 4);
        req.getSession().setAttribute("member_captcha_code", captcha.getCode());

        // 设置响应头
        resp.setContentType("image/jpeg");
        // 清空缓存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        // 将验证码图片写入响应流
        captcha.write(resp.getOutputStream());
    }

    //      跳转用户登录页面
    @GetMapping("/login")
    public String login() {
        return "front/common/login";
    }
    //      用户退出页面,重定向到首页
    @GetMapping("/logout")
    public String logout(HttpSession session,HttpServletRequest req) throws IOException {
        if(session.getAttribute("member_captcha_code") != null) {
            session.removeAttribute("member_captcha_code");
            session.invalidate();
        }
        return "redirect:"+req.getContextPath()+"/vm/front/index";
    }

    //        进行前端账号密码校验
    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<JsonResult> login(@Validated MemberLogin memberLogin, HttpSession session) {
        String correctCapt = (String) session.getAttribute("member_captcha_code");
        if (correctCapt == null) {
            return ResponseEntity.badRequest().body(JsonResult.fail("验证码已过期，请重新获取"));
        }
        if (!memberLogin.getCaptcha().equals(correctCapt)) { //    验证码校验
            return ResponseEntity.badRequest().body(JsonResult.fail("验证码不正确"));
        } else {
            Member member = memberService.findByAccount(memberLogin.getAccount());
            if (member == null) {
                return ResponseEntity.ok().body(JsonResult.fail("账号不存在，请注册"));
            } else {

                PasswordEncryptor pe = new StrongPasswordEncryptor();
                if (!pe.checkPassword(memberLogin.getPassword(), member.getPassword())) {
                    return ResponseEntity.ok().body(JsonResult.fail("密码不正确"));
                } else {
                    session.setAttribute("current_member_login", member);
                    return ResponseEntity.ok().body(JsonResult.successData(member));
                }
            }
        }
    }

    //        跳转用户注册页面
    @GetMapping("/register")
    public String register() {
        return "front/common/register";
    }

    //        进行前端账号注册校验
    @PostMapping(value = "/register", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<JsonResult> register(@Validated Member member) {
        if (member == null) {
            return ResponseEntity.noContent().build();
        }
        Member member1 = memberService.findByAccount(member.getAccount());
        if (member1 != null) {
            return ResponseEntity.ok().body(JsonResult.fail("账户已存在，请登录"));
        } else {
            boolean success = memberService.add(member);
            if (success) {
                return ResponseEntity.ok().body(JsonResult.success("注册成功！现跳转登录页登录"));
            } else {
                return ResponseEntity.ok().body(JsonResult.fail("创建账户失败"));
            }
        }
    }


    //    支付宝异步请求,不能拦截，返回text.html,加Response就不返回模板文件名了
    @PostMapping(value = "/alipay/notify",produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> params) throws AlipayApiException {

        //校验,传给支付宝的信息对不对
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayPublicKey, "UTF-8", "RSA2");
        if (signVerified) {
//            // 写自己的处理业务逻辑
            String orderNo = params.get("out_trade_no");//订单号
            Order order = this.orderService.findByOrderNo(orderNo);

            Order od = new Order();
            od.setId(order.getId());
            od.setState(OrderState.PAYED);//修改为已支付
            this.orderService.patch(od);//只修改订单状态

            //System.out.println(JSONObject.toJSONString(params));
            return "success";
        } else {
            return "fail";
        }
    }



    //      用户账户页面
    @GetMapping("/account")
    public String account(HttpSession session, Map<String, Object> map) {
        Member member = (Member) session.getAttribute("current_member_login");
        List<Order> orders=this.orderService.findByMemberId(member.getId());
        List<MemberAddress> mas=memberAddrService.findByMemberId(member.getId());
        map.put("mas", mas);
        map.put("orders", orders);
        return "front/account/account";
    }
    //      用户新增会员地址页面
    @GetMapping("/account/addMemAddr")
    public String addMemAddr(HttpSession session, Map<String, Object> map) {
        return "front/account/addMemAddr";
    }

    //      关于商城页面
    @GetMapping("/about")
    public String about() {
        return "front/common/about";
    }

    
    //      购物指南页面
    @GetMapping("/purchase-guide")
    public String pagePurchaseGuide() {
        return "front/common/purchase-guide";
    }

    //      服务条款页面
    @GetMapping("/terms")
    public String pageTerms() {
        return "front/common/terms";
    }

    //         跳转隐私政策页面
    @GetMapping("/privacy-policy")
    public String privacyPolicy() {
        return "front/common/privacy-policy";
    }

}
